package com.industrial.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;

import com.industrial.app.domain.BizIndustryAdded;
import com.industrial.app.excel.entity.BizIndustryAddedExcelEntity;
import com.industrial.app.mapper.BizIndustryAddedFormalMapper;
import com.industrial.app.mapper.BizIndustryAddedMapper;
import com.industrial.app.service.IBizIndustryAddedService;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.system.api.domain.SysDictData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分行业工业增加值同比Service业务层处理
 * 
 * @author Zhou_S
 * @date 2024-01-02
 */
@Service
public class BizIndustryAddedServiceImpl implements IBizIndustryAddedService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private BizIndustryAddedMapper bizIndustryAddedMapper;
    @Autowired
    private BizIndustryAddedFormalMapper bizIndustryAddedFormalMapper;

    /**
     * 查询分行业工业增加值同比
     * 
     * @param baseId 分行业工业增加值同比主键
     * @return 分行业工业增加值同比
     */
    @Override
    public BizIndustryAdded selectBizIndustryAddedByBaseId(String baseId)
    {
        return bizIndustryAddedMapper.selectBizIndustryAddedByBaseId(baseId);
    }

    /**
     * 查询分行业工业增加值同比列表
     * 
     * @param bizIndustryAdded 分行业工业增加值同比
     * @return 分行业工业增加值同比
     */
    @Override
    public List<BizIndustryAdded> selectBizIndustryAddedList(BizIndustryAdded bizIndustryAdded)
    {
        return bizIndustryAddedMapper.selectBizIndustryAddedList(bizIndustryAdded);
    }

    /**
     * 新增分行业工业增加值同比
     * 
     * @param bizIndustryAdded 分行业工业增加值同比
     * @return 结果
     */
    @Override
    public int insertBizIndustryAdded(BizIndustryAdded bizIndustryAdded)
    {
        bizIndustryAdded.setBaseId(IdUtil.simpleUUID());
        bizIndustryAdded.setBaseCreateTime(new Date());
        DateTime datesTimes= DateUtil.parse(bizIndustryAdded.getBaseMonth(),"yyyy年MM月");
        bizIndustryAdded.setDates(DateUtil.format(datesTimes,"yyyy-MM"));
        return bizIndustryAddedMapper.insertBizIndustryAdded(bizIndustryAdded);
    }

    /**
     * 修改分行业工业增加值同比
     * 
     * @param bizIndustryAdded 分行业工业增加值同比
     * @return 结果
     */
    @Override
    public int updateBizIndustryAdded(BizIndustryAdded bizIndustryAdded)
    {
        DateTime datesTimes= DateUtil.parse(bizIndustryAdded.getBaseMonth(),"yyyy年MM月");
        bizIndustryAdded.setDates(DateUtil.format(datesTimes,"yyyy-MM"));
        return bizIndustryAddedMapper.updateBizIndustryAdded(bizIndustryAdded);
    }

    /**
     * 批量删除分行业工业增加值同比
     * 
     * @param baseIds 需要删除的分行业工业增加值同比主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustryAddedByBaseIds(String[] baseIds)
    {
        return bizIndustryAddedMapper.deleteBizIndustryAddedByBaseIds(baseIds);
    }

    /**
     * 删除分行业工业增加值同比信息
     * 
     * @param baseId 分行业工业增加值同比主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustryAddedByBaseId(String baseId)
    {
        return bizIndustryAddedMapper.deleteBizIndustryAddedByBaseId(baseId);
    }

    /**
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult transferDataInOneClick() {
        List<BizIndustryAdded> bizIndustryAddeds = bizIndustryAddedMapper.selectBizIndustryAddedAllData();
        int count = 0;
        List<BizIndustryAdded> list = new ArrayList<>();
        try{
            for(BizIndustryAdded item : bizIndustryAddeds){
                list.add(item);
                count++;
                if(count >= 100){
                    bizIndustryAddedFormalMapper.batchInsertBizIndustryAdded(list);
                    list.clear();
                }
            }
            if(!list.isEmpty()){
                bizIndustryAddedFormalMapper.batchInsertBizIndustryAdded(list);
                list.clear();
            }
            return AjaxResult.success();
        }catch (DuplicateKeyException e){
            return AjaxResult.warn("数据存在突冲,您可能已经转移过数据");
        } catch (Exception e){
            return AjaxResult.error("未知错误");
        }
    }

    /**
     *
     */
    @Override
    public void clearAllTableData() {
        bizIndustryAddedMapper.clearAllTableData();
    }

    /**
     * <p>
     * 查询数据库中数据的日期(year_month字段)并进行去重复操作<br/>
     * 主要用于的是APP端左上角的日期过滤
     * </p>
     *
     * @return 日期的数组
     */
    @Override
    public List<String> getUniqueDatesFromDatabase() {
        List<String> uniqueDatesFromDatabase = bizIndustryAddedMapper.getUniqueDatesFromDatabase();
        if(!uniqueDatesFromDatabase.isEmpty()){
            //Mysql中去重关键字和排序不能对同一字段同时使用，这里通过代码来去重
            List<String> collect = uniqueDatesFromDatabase.stream().distinct().collect(Collectors.toList());
            collect = collect.stream().map(item -> {
                String[] split = item.split("-");
                return split[0] + "年" + split[1] + "月";
            }).collect(Collectors.toList());
            return collect;
        }
        return uniqueDatesFromDatabase;
    }

    /**
     * <p>
     * 导入分行业工业增加值同比数据
     * </p>
     *
     * @param absoluteExcelPath
     * @param yearMonth
     * @return 导入是否成功
     */
    @Override
    public AjaxResult importExcel(String absoluteExcelPath, String yearMonth) {
        List<BizIndustryAddedExcelEntity> excelDataArgs = EasyExcel.read(absoluteExcelPath).head(BizIndustryAddedExcelEntity.class).headRowNumber(5).sheet().doReadSync();

        try{
            if(excelDataArgs.isEmpty()){
                logger.warn("分行业工业增加值同比数据");
                return AjaxResult.warn("分行业工业增加值同比数据停止导入,原因:未加载到Excel中的数据");
            }else{
                List<BizIndustryAdded> list = new ArrayList<>();
                List<SysDictData> industryIndicatorsDict = DictUtils.getDictCache("industry_indicators");
                if(industryIndicatorsDict == null || industryIndicatorsDict.isEmpty()){
                    logger.warn("分市工业增加值数据停止导入");
                    return AjaxResult.warn("分市工业增加值数据停止导入,原因:未找到行业指标数据");
                }
                Map<String, String> industryIndicatorsDictMap = industryIndicatorsDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, v -> ""));

                for(BizIndustryAddedExcelEntity item : excelDataArgs){
                    String noSpaceStr = StringUtils.trimAllWhitespace(item.getIndustryIndicators());
                    if(!industryIndicatorsDictMap.containsKey(noSpaceStr)){
                        continue;
                    }
                    BizIndustryAdded bizIndustryAdded = new BizIndustryAdded();
                    bizIndustryAdded.setBaseId(IdUtil.simpleUUID());
                    bizIndustryAdded.setBaseCreateTime(DateUtils.getNowDate());
                    bizIndustryAdded.setBaseMonth(yearMonth);
                    BeanUtil.copyProperties(item,bizIndustryAdded);
                    String regionCode = DictUtils.getDictValue("industry_indicators", item.getIndustryIndicators());
                    bizIndustryAdded.setIndustryIndicators(regionCode);
                    list.add(bizIndustryAdded);
                }
                if(list.isEmpty()){
                    logger.warn("过滤后没有符合要求的数据！");
                }else{
                    bizIndustryAddedMapper.batchInsertBizIndustryAdded(list);
                }
            }
        }catch (Exception e){
            logger.error("导入分市工业增加值数据时出现异常,执行回滚");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.warn("导入失败");
        }
        return AjaxResult.success();
    }

    /**
     * @return
     */
    @Override
    public List<BizIndustryAdded> selectBizIndustryAddedListNoParams() {
        return bizIndustryAddedMapper.selectBizIndustryAddedListNoParams();
    }
}
